// ./mongodb/manager/user/userManager.js
const Router = require("koa-router");
const { UserManager } = require("../../mongodb/manager");
const config = require("../../config.js");
const { verifyToken } = require("../../middleware");
const jwt = require("jsonwebtoken");
// const { promisify } = require("util");

// 创建路由对象
router = new Router();

// 设置文档标签
/**
 * @swagger
 * tags:
 *   name: User
 *   description: 用户接口
 */

// 添加用户接口(需要登陆状态+需要管理员权限)
/**
 * @swagger
 * /users:
 *   post:
 *     tags: [User]
 *     summary: 添加用户
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - password
 *               - username
 *               - role
 *             properties:
 *               email:
 *                 type: string
 *                 format: email
 *                 example: limou@example.com
 *               password:
 *                 type: string
 *                 minLength: 8
 *                 example: 123456
 *               username:
 *                 type: string
 *                 example: limou
 *     responses:
 *       201:
 *         description: 用户注册成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 _id:
 *                   type: string
 *                   description: 用户唯一标识符
 *                 email:
 *                   type: string
 *                   format: email
 *                 username:
 *                   type: string
 *                 role:
 *                   type: string
 *       400:
 *         description: 用户注册失败，可能是邮箱已存在或参数不正确
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 */
router.post("/", verifyToken("admin"), async (ctx) => {
  try {
    const user = await UserManager.createUser(ctx.request.body);
    ctx.status = 200; // 设置响应状态
    ctx.body = user; // 设置响应体
  } catch (error) {
    ctx.status = 400; // 设置错误状态
    ctx.body = { message: error.message }; // 设置错误响应体
  }
});

// 修改用户接口(需要登陆状态+需要管理员权限)
/**
 * @swagger
 * /users:
 *   put:
 *     summary: 根据邮箱或昵称更新用户信息
 *     description: 根据邮箱或昵称更新用户信息，支持部分更新
 *     tags: [User]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - email
 *               - updateData
 *             properties:
 *               email:
 *                 type: string
 *                 description: 用户邮箱
 *                 example: limou@example.com
 *               username:
 *                 type: string
 *                 description: 用户昵称
 *                 example: limou
 *               updateData:
 *                 type: object
 *                 required:
 *                   - password
 *                 properties:
 *                   password:
 *                     type: string
 *                     description: 新密码
 *                     example: newpassword123
 *                   role:
 *                     type: string
 *                     description: 用户角色
 *                     example: admin
 *     responses:
 *       200:
 *         description: 成功更新用户信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 _id:
 *                   type: string
 *                   description: 更新后的用户唯一标识符
 *                 email:
 *                   type: string
 *                   format: email
 *                 username:
 *                   type: string
 *                 role:
 *                   type: string
 *       404:
 *         description: 用户未找到
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'User not found'
 *       400:
 *         description: 请求参数不正确
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'Email or username is required.'
 */
router.put("/", verifyToken("admin"), async (ctx) => {
  const { email, username } = ctx.request.body; // 查询字段
  const { updateData } = ctx.request.body; // 更新字段

  let user;

  // 查找
  if (email) {
    user = await UserManager.getUserByEmail(email);
  } else if (username) {
    // 如果没有根据邮箱找到用户, 尝试根据用户名查找
    user = await UserManager.getUserByUsername(username);
  } else {
    ctx.status = 400;
    ctx.body = { message: "Email or username is required." };
    return;
  }

  // 更新
  try {
    const updatedUser = await UserManager.updateUser(user._id, updateData);
    ctx.status = 200;
    ctx.body = { message: "修改成功", updatedUser };
  } catch (error) {
    ctx.status = 404;
    ctx.body = { message: error.message };
  }
});

// 删除用户接口(需要登陆状态+需要管理员权限)
/**
 * @swagger
 * /users:
 *   delete:
 *     summary: 根据邮箱和昵称删除用户
 *     description: 根据邮箱和昵称标记删除用户
 *     tags: [User]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               email:
 *                 type: string
 *                 description: 用户邮箱
 *                 example: limou@example.com
 *               username:
 *                 type: string
 *                 description: 用户昵称
 *                 example: limou
 *     responses:
 *       200:
 *         description: 成功标记用户删除
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'User successfully marked as deleted.'
 *       404:
 *         description: 用户未找到
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'User not found'
 *       400:
 *         description: 请求参数不正确，需提供邮箱或昵称
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'Email or username is required.'
 */
router.delete("/", verifyToken("admin"), async (ctx) => {
  const { email, username } = ctx.request.body;

  // 检查请求体，确保有两个参数
  if (!email && !username) {
    ctx.status = 400;
    ctx.body = { message: "Email or username is required." };
    return;
  }

  let user;

  // 根据邮箱查找用户
  if (email) {
    user = await UserManager.getUserByEmail(email);
  }
  // 如果未找到，根据用户名查找用户
  else if (username) {
    user = await UserManager.getUserByUsername(username);
  }

  // 如果用户不存在，返回错误
  if (!user) {
    ctx.status = 404;
    ctx.body = { message: "User not found" };
    return;
  }

  // 使用已存在的标记删除方法
  try {
    await UserManager.softDeleteUser(user._id);
    ctx.status = 200;
    ctx.body = { message: "User successfully marked as deleted." };
  } catch (error) {
    ctx.status = 500; // 处理可能的服务器错误
    ctx.body = { message: "Failed to mark user as deleted." };
  }
});

// 查找用户列表接口(需要登陆状态+需要管理员权限)
/**
 * @swagger
 * /users/list:
 *   get:
 *     summary: 获取所有未删除用户
 *     description: 返回所有未删除的用户对象列表
 *     tags: [User]
 *     responses:
 *       200:
 *         description: 成功获取未删除用户列表
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   _id:
 *                     type: string
 *                     description: 用户ID
 *                     example: '60d9b7eec9f74a001f9e9275'
 *                   email:
 *                     type: string
 *                     format: email
 *                     example: 'limou@example.com'
 *                   username:
 *                     type: string
 *                     example: 'limou'
 *                   role:
 *                     type: string
 *                     example: 'user'
 *                   deleted:
 *                     type: boolean
 *                     example: false
 *       500:
 *         description: 服务器内部错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'Failed to retrieve active users.'
 */
router.get("/list", verifyToken("admin"), async (ctx) => {
  try {
    const users = await UserManager.getAllActiveUsers();
    ctx.status = 200; // 设置响应状态
    ctx.body = users; // 设置响应体
  } catch (error) {
    ctx.status = 500; // 设置错误状态
    ctx.body = { message: "Failed to retrieve active users." }; // 设置错误响应体
  }
});

// 登入用户接口
/**
 * @swagger
 * /users/login:
 *   post:
 *     summary: 登入用户
 *     tags: [User]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               email:
 *                 type: string
 *                 example: limou@example.com
 *               password:
 *                 type: string
 *                 example: 123456
 *     responses:
 *       200:
 *         description: Login successful
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 user:
 *                   type: object
 *                   additionalProperties: true
 *       401:
 *         description: Invalid email or password
 *       500:
 *         description: Server error
 */
router.post("/login", async (ctx) => {
  const { email, password } = ctx.request.body;

  try {
    const user = await UserManager.validateUser(email, password);
    if (!user) {
      ctx.status = 401; // 未授权
      ctx.body = { message: "Invalid email or password" };
      return;
    }

    // 创建 JWT token, 设置有效时间为一天
    const token = jwt.sign({ id: user._id }, config.jwtSecret, {
      expiresIn: "1d",
    });

    // 设置 cookie, 存储 token
    ctx.cookies.set("token", token, {
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    });

    ctx.body = { message: "Login successful", user };
  } catch (error) {
    ctx.status = 500; // 服务器错误
    ctx.body = { message: error.message };
  }
});

// 登出用户接口(需要登陆状态)
/**
 * @swagger
 * /users/logout:
 *   post:
 *     summary: 登出用户
 *     tags: [User]
 *     responses:
 *       200:
 *         description: Logout successful
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *       401:
 *         description: Unauthorized access
 */
router.post("/logout", verifyToken("user"), async (ctx) => {
  ctx.cookies.set("token", null); // 清除 cookie
  ctx.body = { message: "Logout successful" };
});

// 获取当前登录用户信息接口(需要登陆状态)
/**
 * @swagger
 * /users/me:
 *   get:
 *     summary: 获取当前登录用户信息
 *     tags: [User]
 *     responses:
 *       200:
 *         description: 返回当前登录用户信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 user:
 *                   type: object
 *                   additionalProperties: true
 *       401:
 *         description: Unauthorized - 用户未登录或 token 无效
 */
router.get("/me", verifyToken("user"), async (ctx) => {
  ctx.body = { user: ctx.state.user }; // 返回中间件验证通过的用户信息
});

module.exports = { router };
